<template>
	<view class="contont">
		<nav-bar :title="pageInfo.navbarTitle" :iconLeft="true" />
		<uni-forms :model="form" :rules="rules" ref="refForm" labelAlign="right" label-width="90px">
			<view class="content-bgc">
				<view class="b-con">
					<uni-forms-item label="不良品入库单号" name="code" required>
						<view style="display: flex;gap:20rpx">
							<uni-easyinput v-model="form.code" placeholder="请输入不良品入库单号" class="iptBor" :inputBorder="false"
								:disabled="switchCode" />
							<view style="margin-left: 20rpx" v-show="pageInfo.type == 'add'">
								<u-switch v-model="switchCode" @change="switchChange" size="20" />
								自动生成
							</view>
						</view>

					</uni-forms-item>
					<view class="hint-text">只有“已审核”状态的生产单，才会出现在下拉框中</view>
					<uni-forms-item label="生产单号" name="order" required>
						<uni-data-select mode="underline" placeholder="请选择生产单" v-model="form.order" :localdata="order_list"
							:clear="false" :disabled="pageInfo.type == 'edit'" @change="order_change" />
					</uni-forms-item>
					<uni-forms-item label="备注：" name="desc">
						<uni-easyinput type="textarea" v-model="form.desc" placeholder="请输入备注" />
					</uni-forms-item>
				</view>
				<view class="b-con">
					<u-cell-group :border="false">
						<u-cell :isLink="true" :border="false" :title="`产品数量（${form.product_list.length}）`"
							@click="car_popupShow = true">
							<template #value>
								<view class="cell-text">点击查看 </view>
							</template>
						</u-cell>
					</u-cell-group>
				</view>
			</view>
			<custom-popup :popupShow="car_popupShow" mode="bottom" :title="'不良品'" class="car-popup-custom"
				@close="car_popupShow = false" height="70vh">
				<z-paging v-if="car_popupShow" ref="paging_car" :refresher-enabled="false" :loading-more-enabled="false" :fixed="false"
					v-model="form.product_list" @query="queryList_car">
					<template #top>
						<view class="zpagin_top">
							<view class="search">
								<view class="hint-text">本期入库数量应在 0 和 (已完成数量 - 已入库数量) 之间</view>
							</view>
						</view>
					</template>
					<uni-card v-for="(item, index) in form.product_list" :key="index" :title="item.name" :sub-title="item.code"
						margin="5px" spacing="0">
						<view class="ctent">规格：{{ item.specification }}</view>
						<view class="con">
							<view class="ctent">基本单位：{{ item.unit_main }}</view>
							<view class="ctent">生产数量：{{ item.num }}</view>
						</view>
						<view class="con">
							<view class="ctent">已完成数量：{{ item.finish_num }}</view>
							<view class="ctent">不良品已入库：{{ item.up_num }}</view>
						</view>
						<uni-forms-item label="入库仓库：" :name="`product_list[${index}].warehouse`" required
							:rules="[{ required: true, errorMessage: `请选择【${item.name}】的入库仓库` }]">
							<uni-data-select mode="underline" placeholder="请选择入库仓库" v-model="item.warehouse"
								:localdata="warehouse_list" :clear="false" />
						</uni-forms-item>
						<view class="con">
							<view class="ctent" style="flex: none;">本期入库数量：</view>
							<custom-num-box v-model="item.now_num" :min="0" @change="changeNum($event, item)"
								:asyncChange="true"></custom-num-box>
						</view>
					</uni-card>
					<template #bottom>
						<view style="padding: 20rpx;">
							<up-button type="primary" text="提交" @click="save" />
						</view>
					</template>
				</z-paging>
			</custom-popup>
		</uni-forms>
	</view>
</template>
<script setup>
import { reactive, ref, getCurrentInstance } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import pBadnessApi from '../../../api/production/p_badness'
import { generateCode, debounce } from '@/utils/index.js';

//页面标题
const pageInfo = reactive({
	navbarTitle: '不良品入库',
	type: '',
	edit_id: null,
})

onLoad(option => {
	get_warehouse_list()
	get_order_list()
	pageInfo.type = option.type
	if (option.type == 'edit') {
		pageInfo.navbarTitle = `${pageInfo.navbarTitle}(修改)`
		get_detail(option.id)
		pageInfo.edit_id = option.id
	} else {
		pageInfo.navbarTitle = `${pageInfo.navbarTitle}(新增)`
		form.code = generateCode('BL')
	}
})

//自动生成按钮
const switchCode = ref(true);
function switchChange(v) {
	if (v) {
		form.code = generateCode('BL')
	}
};

const refForm = ref(null);
const form = reactive({
	code: '',
	order: null,
	get_user_id: '',
	desc: '',
	product_list: []
})
const fields = Object.keys(form)
const rules = {
	code: { rules: [{ required: true, errorMessage: '请输入不良品入库单号' }] },
	order: { rules: [{ required: true, type: 'number', errorMessage: '请选择生产单' }] },
}


function get_detail(id) {
	pBadnessApi.production_flaw_detail(id).then(res => {
		const record = uni.$lodash.pick(res, fields)
		Object.assign(form, record)
		pBadnessApi.production_flaw_product({ order_flaw_id: id }).then(res2 => {
			form.product_list = res2.results.map(v => {
				return {
					id: v.order_product.product.id,
					order_product_id: v.order_product.id,
					code: v.order_product.product.code,
					name: v.order_product.product.name,
					specification: v.order_product.product.specification,
					unit_main: v.order_product.product.unit_main,
					num: v.num,
					finish_num: v.finish_num,
					up_num: v.up_num,
					now_num: v.now_num,
					warehouse: v.warehouse
				}
			})

		})
	})
}
function order_change(v) {
	pBadnessApi.production_order_product_detail({ order__id: v }).then(res => {
		form.product_list = res.results.map(v => {
			return {
				id: v.product.id,
				order_product_id: v.id,
				code: v.product.code,
				name: v.product.name,
				specification: v.product.specification,
				unit_main: v.product.unit_main,
				num: v.num,
				now_num: 0,
				warehouse: null,
				finish_num: v.finish_num,
				up_num: v.flaw_num
			}
		})
	})
}
function changeNum(e, row) {
	if (!row.warehouse) {
		return uni.$u.toast('请选择仓库')
	}
	if (e.value > row.finish_num - row.up_num) {
		row.now_num = row.finish_num - row.up_num
		return uni.$u.toast('本期入库数量应在 0 和 (已完成数量 - 已入库数量) 之间')
	}
	row.now_num = e.value
}
const paging_car = ref(null)
const car_popupShow = ref(false)
function queryList_car() {
	paging_car.value.complete(form.product_list);
}


//提交操作
function save() {
	refForm.value.validate().then(() => {
		const params = uni.$lodash.cloneDeep(form) // 深拷贝一份form表单
		if (pageInfo.type == 'add') {
			pBadnessApi.post_production_flaw(params).then(res => {
				uni.$u.toast('添加成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		} else {
			//修改
			pBadnessApi.patch_production_flaw(params, pageInfo.edit_id).then((res) => {
				uni.$u.toast('修改成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		}

	}).catch((error) => {
		uni.$u.toast(error[0].errorMessage);
	})
}

const warehouse_list = ref([])
function get_warehouse_list() {
	pBadnessApi.get_warehouse().then(res => {
		warehouse_list.value = res.results.map(v => ({
			text: v.name,
			value: v.id
		}))
	})
}

const order_list = ref([])
function get_order_list() {
	const params = { page: 1, page_size: 99999, status: 2 };
	pBadnessApi.get_production_order(params).then(res => {
		order_list.value = res.results.map(v => ({
			text: v.code,
			value: v.id
		}))
	})
}


//返回上一级并刷新上一级页面
function backRefsh() {
	uni.navigateBack({
		delta: 1, // 返回的页面层数，1 表示返回上一级
		success: () => {
			uni.$bus.useBusEmit('w_in_badness:refresh')
		}
	})
}
</script>

<style lang="scss" scoped></style>